package com.pug.gateway.rest;

import cn.hutool.core.util.StrUtil;
import com.pug.gateway.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import xq.pug.common.result.R;

/**
 * @author RenGaoshuai
 * @date 2023/5/16 15:43
 * @description
 */
@RestController
@RequestMapping("/auth")
public class TokenController {

    private static final String BASIC = "Basic ";

    @Autowired
    private TokenService tokenService;


    @Value("${ecs.token.scope:read}")
    private String scope;
    /**
     * 授权模式（授权码模式 客户端模式 密码模式 简化模式 自定义模式）
     * 这里选择客户端模式
     */
    @Value("${ecs.token.grant_type:client_credentials}")
    String grant_type;

    /**
     * 账号1 test_client:test_secret
     * dGVzdF9jbGllbnQ6dGVzdF9zZWNyZXQ=
     * <p>
     * 基于redis+jwt的token方式
     *
     * @param exchange
     * @return
     */
    @PostMapping("/getToken")
    public R<String> getToken(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        String account = headers.getFirst("Account");
        if (StrUtil.isBlank(account)) {
            return R.ofFail("账户信息不存在请检查");
        }
        String authorization = BASIC + account;

        //生成token
        String token = tokenService.getToken(authorization);
        return R.ofSuccess(token);
    }
}
